using System;
using System.Data;
using System.Collections;
using System.Collections.Generic;

using Framework;

namespace SchemaMonitor
{
    [Serializable()]
    public partial class CSignature : CBaseDynamicM2M, IComparable<CSignature>
    {
        #region Constructors
        //Public (Copy Constructor)
        public CSignature(CSignature original, CDataSrc target)
        {
            //Database Connection
            m_dataSrc = target;

            //Copy fields
            _sigHash = original.SigHash;
            _sigTypeId = original.SigTypeId;
            _sigDiscoveryId = original.SigDiscoveryId;
            _sigDescription = original.SigDescription;
            _sigCreated = original.SigCreated;
        }

        //Protected (Datareader/Dataset)
        protected CSignature(CDataSrc dataSrc, IDataReader dr) : base(dataSrc, dr) {}
        protected CSignature(CDataSrc dataSrc, DataRow     dr) : base(dataSrc, dr) {}
        #endregion

        #region Default Values
        protected override void InitValues_Auto()
        {
            //Null-Equivalent values (except String.Empty, as nulls tend to be inconvenient for string types)
            _sigHash = Guid.Empty;
            _sigTypeId = int.MinValue;
            _sigDiscoveryId = 0;
            _sigDescription = string.Empty;
            _sigCreated = DateTime.MinValue;
        }
        #endregion

        #region Members
        protected Guid _sigHash;
        protected int _sigTypeId;
        protected byte _sigDiscoveryId;
        protected string _sigDescription;
        protected DateTime _sigCreated;
        #endregion

        #region Properties - Column Values
        //Primary Key Columns
        public Guid SigHash    {   get { return _sigHash; } set { _sigHash = value; }    }
        public int SigTypeId    {   get { return _sigTypeId; } set { _sigTypeId = value; }    }

        //Table Columns (Read/Write)
        public byte SigDiscoveryId    {   get { return _sigDiscoveryId; } set { _sigDiscoveryId = value; }    }
        public string SigDescription    {   get { return _sigDescription; } set { _sigDescription = value; }    }
        public DateTime SigCreated    {   get { return _sigCreated; } set { _sigCreated = value; }    }

        //View Columns (ReadOnly)

        #endregion

        #region MustOverride Methods
        //Schema Information
        public const string TABLE_NAME      = "Signatures";
        public const string VIEW_NAME       = "";         //Used to override this.ViewName { get }
        public const string ORDER_BY_COLS   = "SigDescription";   //See the CompareTo method below (Sql-based sorting should match In-Memory sorting)
        public const string SORTING_COLUMN  = "";
        public override string TableName {    get { return TABLE_NAME; } }
        protected override string OrderByColumns {    get { return ORDER_BY_COLS; } }

        //CompareTo Interface (Default Sort Order)
        public int CompareTo(CSignature other) {   return this.SigDescription.CompareTo(other.SigDescription) ;  }

        //Primary Key Information
        protected override string PrimaryKeyName    {   get { return "SigHash";    } }
        protected override string SecondaryKeyName  {   get { return "SigTypeId";  } }        protected override object PrimaryKeyValue 
        {
              get { return _sigHash; }
              set { _sigHash = (Guid)value; }
        }
        protected override object SecondaryKeyValue 
        {
              get { return _sigTypeId; }
              set { _sigTypeId = (int)value; }
        }

        //Factory Methods - Object
        protected override CBase MakeFrom(DataRow row)        {   return new CSignature(this.DataSrc, row);     }
        protected override CBase MakeFrom(IDataReader dr)     {   return new CSignature(this.DataSrc, dr);      }

        //Factory Methods - List
        protected override IList MakeList()                   {   return new CSignatureList();                  }
        protected override IList MakeList(int capacity)       {   return new CSignatureList(capacity);          }

        //Convert from ADO to .Net
        protected override void ReadColumns(IDataReader dr)
        {
            _sigHash = CAdoData.GetGuid(dr, "SigHash");
            _sigTypeId = CAdoData.GetInt(dr, "SigTypeId");
            _sigDiscoveryId = CAdoData.GetByte(dr, "SigDiscoveryId");
            _sigDescription = CAdoData.GetStr(dr, "SigDescription");
            _sigCreated = CAdoData.GetDate(dr, "SigCreated");
        }
        protected override void ReadColumns(DataRow dr)
        {
            _sigHash = CAdoData.GetGuid(dr, "SigHash");
            _sigTypeId = CAdoData.GetInt(dr, "SigTypeId");
            _sigDiscoveryId = CAdoData.GetByte(dr, "SigDiscoveryId");
            _sigDescription = CAdoData.GetStr(dr, "SigDescription");
            _sigCreated = CAdoData.GetDate(dr, "SigCreated");
        }

        //Parameters for Insert/Update    
        protected override CNameValueList ColumnNameValues()
        {
            CNameValueList data = new CNameValueList();
            data.Add("SigHash", CAdoData.NullVal(_sigHash));
            data.Add("SigTypeId", CAdoData.NullVal(_sigTypeId));
            data.Add("SigDiscoveryId", CAdoData.NullVal(_sigDiscoveryId));
            data.Add("SigDescription", CAdoData.NullVal(_sigDescription));
            data.Add("SigCreated", CAdoData.NullVal(_sigCreated));
            return data;
        }
        #endregion

        #region Queries - SelectAll/SelectWhere (inherited methods, cast only)
        //Normally used to load the cache
        public    new CSignatureList SelectAll()                                                                           {   return (CSignatureList)base.SelectAll();        }
        public    new CSignatureList SelectAll(string orderBy)                                                             {   return (CSignatureList)base.SelectAll(orderBy); }

        //Sometimes use a custom query to load the cache
        protected new CSignatureList SelectWhere(string colName, ESign sign, object colValue)                              {   return (CSignatureList)base.SelectWhere(colName, sign, colValue);                  }
        protected new CSignatureList SelectWhere(CCriteria where)                                                          {   return (CSignatureList)base.SelectWhere(where);                                    }
        protected new CSignatureList SelectWhere(CCriteriaList where)                                                      {   return (CSignatureList)base.SelectWhere(where);                                    }
        protected new CSignatureList SelectWhere(CCriteriaList where, string tableOrJoin)                                  {   return (CSignatureList)base.SelectWhere(where, tableOrJoin, this.OrderByColumns);  }
        protected new CSignatureList SelectWhere(CCriteriaList where, string tableOrJoin, string orderBy)                  {   return (CSignatureList)base.SelectWhere(where, tableOrJoin, orderBy);              }
        [Obsolete("Arbitrary where-clause is not necessary portable or safe from sql injection attacks. Consider using the parameterised query interfaces (or a stored proc)")]
        protected new CSignatureList SelectWhere(string unsafeWhereClause)                                                 {   return (CSignatureList)base.SelectWhere(unsafeWhereClause);                        }
        protected     CSignatureList SelectById(Guid sigHash, int sigTypeId)                                               {   return (CSignatureList)base.SelectById(sigHash, sigTypeId);                    }
        protected     CSignatureList SelectByIds(List<Guid> ids)                                         {   return (CSignatureList)base.SelectByIds(ids);                                      }

        //Select Queries - Paged
        protected new CSignatureList SelectAll(  CPagingInfo pi)                                               {    return (CSignatureList)base.SelectAll(  pi);                          }
        protected new CSignatureList SelectWhere(CPagingInfo pi, string name, ESign sign, object value)        {    return (CSignatureList)base.SelectWhere(pi, name, sign, value);       }
        protected new CSignatureList SelectWhere(CPagingInfo pi, CCriteria criteria)                           {    return (CSignatureList)base.SelectWhere(pi, criteria);                }
        protected new CSignatureList SelectWhere(CPagingInfo pi, CCriteriaList criteria)                       {    return (CSignatureList)base.SelectWhere(pi, criteria);                }
        protected new CSignatureList SelectWhere(CPagingInfo pi, CCriteriaList criteria, string viewOrJoin)    {    return (CSignatureList)base.SelectWhere(pi, criteria, viewOrJoin);    }

        //Select Queries - Transactional (Internal scope for use in cascade deletes)
        internal new CSignatureList SelectAll(                                                                                           IDbTransaction tx)  {    return (CSignatureList)base.SelectAll(                                                 tx);    }
        internal new CSignatureList SelectAll(string orderBy,                                                                            IDbTransaction tx)  {    return (CSignatureList)base.SelectAll(orderBy,                                         tx);    }
        internal new CSignatureList SelectWhere(string columnName,               object columnValue,                                     IDbTransaction tx)  {    return (CSignatureList)base.SelectWhere(columnName,              columnValue,          tx);    }
        internal new CSignatureList SelectWhere(string columnName,   ESign sign, object columnValue,                                     IDbTransaction tx)  {    return (CSignatureList)base.SelectWhere(columnName,    sign,     columnValue,          tx);    }
        internal new CSignatureList SelectWhere(                             CCriteria     criteria,                                     IDbTransaction tx)  {    return (CSignatureList)base.SelectWhere(               criteria,                       tx);    }
        internal new CSignatureList SelectWhere(                             CCriteriaList criteria,                                     IDbTransaction tx)  {    return (CSignatureList)base.SelectWhere(               criteria,                       tx);    }
        internal new CSignatureList SelectWhere(                             CCriteriaList criteria, string tableOrJoin,                 IDbTransaction tx)  {    return (CSignatureList)base.SelectWhere(               criteria, tableOrJoin,          tx);    }
        internal new CSignatureList SelectWhere(                             CCriteriaList criteria, string tableOrJoin, string orderBy, IDbTransaction tx)  {    return (CSignatureList)base.SelectWhere(               criteria, tableOrJoin,          tx);    }
        internal     CSignatureList SelectById(Guid sigHash, int sigTypeId,                                                              IDbTransaction tx)  {    return (CSignatureList)base.SelectById(sigHash, sigTypeId,                         tx);    }
        internal     CSignatureList SelectByIds(List<Guid> ids,                                                        IDbTransaction tx)  {    return (CSignatureList)base.SelectByIds(ids,                                           tx);    }

        //Select Queries - Stored Procs
        protected new CSignatureList MakeList(string storedProcName,                           IDbTransaction txOrNull)    {   return (CSignatureList)base.MakeList(storedProcName,             txOrNull);  }
        protected new CSignatureList MakeList(string storedProcName, object[] parameters,      IDbTransaction txOrNull)    {   return (CSignatureList)base.MakeList(storedProcName, parameters, txOrNull);  }
        protected new CSignatureList MakeList(string storedProcName, CNameValueList parameters,IDbTransaction txOrNull)    {   return (CSignatureList)base.MakeList(storedProcName, parameters, txOrNull);  }
        protected new CSignatureList MakeList(string storedProcName, List<object> parameters,  IDbTransaction txOrNull)    {   return (CSignatureList)base.MakeList(storedProcName, parameters, txOrNull);  }
        protected new CSignatureList MakeList(string storedProcName, int param1,               IDbTransaction txOrNull)    {   return (CSignatureList)base.MakeList(storedProcName, param1,     txOrNull);  }
        protected new CSignatureList MakeList(string storedProcName, string param1,            IDbTransaction txOrNull)    {   return (CSignatureList)base.MakeList(storedProcName, param1,     txOrNull);  }

        //Query Results
        protected new CSignatureList MakeList(DataSet              ds) { return (CSignatureList)base.MakeList(ds);        }
        protected new CSignatureList MakeList(DataTable            dt) { return (CSignatureList)base.MakeList(dt);        }
        protected new CSignatureList MakeList(DataRowCollection  rows) { return (CSignatureList)base.MakeList(rows);      }
        protected new CSignatureList MakeList(IDataReader          dr) { return (CSignatureList)base.MakeList(dr);        }
        protected new CSignatureList MakeList(object           drOrDs) { return (CSignatureList)base.MakeList(drOrDs);    }
        protected new CSignatureList MakeList(byte[]             gzip) { return (CSignatureList)base.MakeList(gzip);      }
        #endregion

        #region Queries - SelectBy[FK] (user-nominated fk/bool columns)
        //Note: These methods should only be used for cascade-deletes, or initialising the cache. Use CSignature.Cache.GetBy... for reqular queries

        //Non-Paged
        protected CSignatureList SelectByDiscoveryId(byte sigDiscoveryId)    {    return SelectWhere(new CCriteriaList("SigDiscoveryId", sigDiscoveryId));    }
        protected CSignatureList SelectByHash(Guid sigHash)    {    return SelectWhere(new CCriteriaList("SigHash", sigHash));    }
        protected CSignatureList SelectByTypeId(int sigTypeId)    {    return SelectWhere(new CCriteriaList("SigTypeId", sigTypeId));    }

        //Paged
        protected CSignatureList SelectByDiscoveryId(CPagingInfo pi, byte sigDiscoveryId)    {    return SelectWhere(pi, new CCriteriaList("SigDiscoveryId", sigDiscoveryId));    }
        protected CSignatureList SelectByHash(CPagingInfo pi, Guid sigHash)    {    return SelectWhere(pi, new CCriteriaList("SigHash", sigHash));    }
        protected CSignatureList SelectByTypeId(CPagingInfo pi, int sigTypeId)    {    return SelectWhere(pi, new CCriteriaList("SigTypeId", sigTypeId));    }

        //Count
        protected int SelectCountByDiscoveryId(byte sigDiscoveryId)   {   return SelectCount(new CCriteriaList("SigDiscoveryId", sigDiscoveryId));     }
        protected int SelectCountByHash(Guid sigHash)   {   return SelectCount(new CCriteriaList("SigHash", sigHash));     }
        protected int SelectCountByTypeId(int sigTypeId)   {   return SelectCount(new CCriteriaList("SigTypeId", sigTypeId));     }

        //Transactional
        internal CSignatureList SelectByDiscoveryId(byte sigDiscoveryId, IDbTransaction tx)    {    return SelectWhere(new CCriteriaList("SigDiscoveryId", sigDiscoveryId), tx);    }
        internal CSignatureList SelectByHash(Guid sigHash, IDbTransaction tx)    {    return SelectWhere(new CCriteriaList("SigHash", sigHash), tx);    }
        internal CSignatureList SelectByTypeId(int sigTypeId, IDbTransaction tx)    {    return SelectWhere(new CCriteriaList("SigTypeId", sigTypeId), tx);    }
        #endregion

        #region Many-To-Many Helper Functions
        //Insert/Delete - NonTransactional
        public static void InsertPair(Guid sigHash, int sigTypeId) {        InsertPair(sigHash, sigTypeId, null); }
        public static int  DeletePair(Guid sigHash, int sigTypeId) { return DeletePair(sigHash, sigTypeId, null); }
        public static bool ExistsPair(Guid sigHash, int sigTypeId) { return ExistsPair(sigHash, sigTypeId, null); }
        
        //Insert/Delete - Transactional
        public static void InsertPair(Guid sigHash, int sigTypeId, IDbTransaction txOrNull) {        InsertPair(sigHash, sigTypeId, txOrNull, CDataSrc.Default); }
        public static int  DeletePair(Guid sigHash, int sigTypeId, IDbTransaction txOrNull) { return DeletePair(sigHash, sigTypeId, txOrNull, CDataSrc.Default); }
        public static bool ExistsPair(Guid sigHash, int sigTypeId, IDbTransaction txOrNull) { return ExistsPair(sigHash, sigTypeId, txOrNull, CDataSrc.Default); }

        //Insert/Delete
        public static void InsertPair(Guid sigHash, int sigTypeId, IDbTransaction txOrNull, CDataSrc dataSrc)
        {
            CSignature pair = new CSignature(dataSrc);
            pair.SigHash = sigHash;
            pair.SigTypeId = sigTypeId;
            pair.Save(txOrNull);
        }
        public static int DeletePair(Guid sigHash, int sigTypeId, IDbTransaction txOrNull, CDataSrc dataSrc)
        {
            CCriteriaList where = new CCriteriaList();
            where.Add("SigHash", sigHash);
            where.Add("SigTypeId", sigTypeId);

            //Faster, but not audited
            //return new CSignature(dataSrc).DeleteWhere(where, txOrNull, true);
            
            //Slower, but audit-trail and other delete logic is preserved e.g. cascade deletes
            CSignatureList list = new CSignature(dataSrc).SelectWhere(where, txOrNull);
            list.DeleteAll(txOrNull);
            return list.Count;
        }
        public static bool ExistsPair(Guid sigHash, int sigTypeId, IDbTransaction txOrNull, CDataSrc dataSrc)
        {
            return new CSignature(dataSrc).SelectById(sigHash, sigTypeId, txOrNull).Count > 0;
        }
        #endregion

        #region Static - Cache Implementation
        public static CSignatureList Cache
        {
            get
            {
                CSignatureList cache = (CSignatureList)CCache.Get(CACHE_KEY);
                if (cache == null)
                {
                    lock (typeof(CSignatureList))
                    {
                        cache = (CSignatureList)CCache.Get(CACHE_KEY);
                        if (cache == null)
                        {
                            cache = LoadCache();
                            CSignature.Cache = cache;
                        }
                    }
                }
                return cache;
            }
            set
            {
                SetCache(value);   //Not locked, because cache gets cleared at anytime anyway
            }
        }

        //Change Management:
        //Clone, modify, and then replace the cache (threadsafe for anything iterating the collection)
        //Note that internal indices are dicarded each time unless handled in constructor and add/remove overrides
        protected override void CacheDelete()
        {
            if (CacheIsNull)
                return;

            lock (typeof(CSignatureList))
            {
                CSignatureList temp = new CSignatureList(Cache);
                int size = temp.Count;
                temp.Remove(this);
                if (size == temp.Count) //Remove might fail if cache was refreshed with new instances. Use old index
                    temp.Remove(CacheGetById(temp));
                Cache = temp;
            }
        }
        protected override void CacheInsert()
        {
            if (CacheIsNull)
                return;

            lock (typeof(CSignatureList))
            {
                CSignatureList temp = new CSignatureList(Cache);
                temp.Add(this);
                SetCache(temp);
            }
        }
        protected override void CacheUpdate()
        {
            if (CacheIsNull)
                return;

            lock (typeof(CSignatureList))
            {
                CSignatureList temp = new CSignatureList(Cache);
                if (!temp.Contains(this))
                {
                    temp.Remove(CacheGetById(temp));
                    temp.Add(this);
                }
                SetCache(temp);
            }
        }
        protected override void CacheClear()
        {
            SetCache(null);
        }
        protected static bool CacheIsNull
        {
            get
            {
                return null == CCache.Get(CACHE_KEY);
            }
        }
        #endregion
        #region ToXml
        protected override void ToXml_Autogenerated(System.Xml.XmlWriter w)
        {
            Store(w, "SigHash", this.SigHash);
            Store(w, "SigTypeId", this.SigTypeId);
            Store(w, "SigDiscoveryId", this.SigDiscoveryId);
            Store(w, "SigDescription", this.SigDescription);
            Store(w, "SigCreated", this.SigCreated);
        }
        #endregion

    }
}
